package com.droidski.taskdb.cli;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;



public class CLI {
	
	public String[] args;
	
	public CLI(String[] args) {
		this.args = args; // CLI.parseArgs(args);
	}

	public CLI(String lineOfArgs) {
		this.args = lineOfArgs.split(" ");
	}

	/**
	 * 'fixes' the args so that quoted args become a single entry
	 * @param args
	 * @return
	 */
	public static String[] parseArgs(String[] args) {
		StringBuffer sb = new StringBuffer();
		for (String s : args ) {
			sb.append(s);
			sb.append(" ");
		}
		StringTokenizer st = new StringTokenizer(sb.toString().trim());
		List<String> argsList = new ArrayList<String>();
		// the command first
		argsList.add(st.nextToken());
		sb = new StringBuffer();
		while ( st.hasMoreTokens() ) {
			String token = st.nextToken();
			if (token.startsWith("-")) {
				String value = sb.toString().trim();
				if ( !"".equals(value) ) {
					argsList.add(sb.toString().trim());
				}
				argsList.add(token);
				sb = new StringBuffer();
			} else {
				sb.append(token);
				sb.append(" ");
			}
		}
		String value = sb.toString().trim();
		if ( !"".equals(value) ) {
			argsList.add(sb.toString().trim());
		}
		args = new String[argsList.size()];
		argsList.toArray(args);
		return args;
		
	}
	
	public int getIntOrDefault(String key, int defaultValue) {
		if ( valueOf(key) == null ) {
			return defaultValue;
		} else {
			try {
				int value = Integer.parseInt( valueOf(key) );
				return value;
			} catch (Exception e) {
				return defaultValue;
			}
		}
	}
	
	public int indexOf(String key) {
		for (int i=0; i<args.length; i++) {
			if ( args[i].equals(key) ) {
				return i;
			}
		}
		return -1;
	}
	
	public String valueOf(String key) {
		int index = indexOf(key);
		if ( index < args.length ) {
			return args[index+1];
		} else {
			return null;
		}
	}
	
	public boolean containsKey(String key) {
		return indexOf(key) > -1;
	}
	
	public String getValue(String key) {
		int index = indexOf(key);
		if ( index == -1 ) {
			return null;
		} else if ( args.length >= index ) {
			String value = args[index+1];
			if ( isKey(value) ) {
				return null;
			} else {
				return value;
				
			}
		} else {
			return null;
		}
	}

	public boolean isKey(String key) {
		return key != null && key.startsWith("-");
	}
	
	public boolean isVerbose() {
		return indexOf("-v") > -1;
	}
	
	/**
	 * returns the string of all values starting at the passed
	 * index - stops when it encounters a key
	 * @param index
	 * @return
	 */
	public String getAllValuesFrom(int index) {
		String value = "";
		for (int i=index; i<args.length; i++) {
			if ( args[i].startsWith("-")) {
				break;
			} else {
				value+=args[i];
				value+=" ";
			}
		}
		return value.trim();
	}
	
	@Override
	public String toString() {
		StringBuffer sb = new StringBuffer();
		for ( String s : args ) {
			sb.append(s);
			sb.append(" ");
		}
		return sb.toString().trim();
	}
		
}
